import { defineStore } from 'pinia'
import { listDictData } from '@/apis/common/common'

export const useAppStore = defineStore('app', () => {
  // 状态栏高度计算
  const { statusBarHeight, windowWidth } = uni.getSystemInfoSync()
  let navBarHeight = 54
  // let navBarHeight = 0
  let menuButtonHeight = 44
  let menuButtonLeft = windowWidth - 60
  // #ifdef MP-WEIXIN
  const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  menuButtonHeight = menuButtonInfo.height
  menuButtonLeft = menuButtonInfo.left
  navBarHeight = menuButtonHeight + (menuButtonInfo.top - statusBarHeight) * 2
  // #endif
  const navAreaHeight = statusBarHeight + navBarHeight

  // app更新
  const updateApp = () => {
    // #ifdef MP-WEIXIN
    const updateManager = uni.getUpdateManager()

    updateManager.onCheckForUpdate((res) => {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })

    updateManager.onUpdateReady((res) => {
      uni.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        },
      })
    })

    updateManager.onUpdateFailed((res) => {
      // 新的版本下载失败
    })
    // #endif
  }

  // 字典数据
  const dictList = shallowRef<Record<string, any[]>>({})
  const dictMap = computed(() => {
    const data = {}
    for (const key in dictList.value) {
      const dict = {}
      dictList.value[key].forEach(item => dict[item.value] = item)
      data[key] = dict
    }
    return data
  })
  const loadDict = async () => {
    dictList.value = await listDictData()
  }

  return {
    statusBarHeight,
    navBarHeight,
    navAreaHeight,
    menuButtonHeight,
    menuButtonLeft,
    updateApp,
    loadDict,
    dictList,
    dictMap,
  }
})
